package com.netty.common.handler;


import com.netty.common.entity.result.Result;
import com.netty.common.enums.ExceptionEnum;
import com.netty.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;


/** 全局异常处理类
 * @author LiuXiaoYu
 * @date 2021/7/19- 14:25
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * @param bizException 自定义异常
     * @return result 通用错误返回
     */
    @ExceptionHandler(BizException.class)
    public Result<ExceptionEnum> handleException(BizException bizException){
        log.warn("业务异常:{}",bizException.getMessage(),bizException);
        return Result.error(bizException.getError(),bizException.getMessage());
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<ExceptionEnum> handlerNoFoundException(Exception e) {
        log.error("请求路径未找到:{}",e.getMessage(), e);
        return Result.error(ExceptionEnum.REQUEST_PATH, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<String> handleDuplicateKeyException(DuplicateKeyException e){
        log.warn("数据库已存在该记录异常:"+e.getMessage(), e);
        return Result.error("数据库中已存在该记录");
    }
    /**Get参数散装参数校验 即不是封装得对象
     * ConstraintViolationException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<ExceptionEnum> handleConstraintViolationException(ConstraintViolationException e) {
        log.warn("参数错误: {}", e.getMessage(), e);
        // 一般只需返回泛化的错误信息，比如“参数错误”
        return Result.error(ExceptionEnum.ERROR_VALID_ARGUMENTS,e.getMessage());
    }

    /**
     * BindException异常（GET 对象校验）
     * Get请求 参数封装Dto 不加@RequestBody注解
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<?> validationBindException(BindException e) {
        log.error("Get请求数据校验Dto参数错误{},异常类型:{}",e.getMessage(),e.getClass());
        Map<String,String> errorMap=new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return Result.error(ExceptionEnum.ERROR_VALID_ARGUMENTS,errorMap);
    }

    /**
     * 处理post请求方式校验
     *  Dto @RequestBody 方式封装json
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handlerValidException(MethodArgumentNotValidException e){
        log.error("Post请求数据校验Dto参数错误{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult=e.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return Result.error(ExceptionEnum.ERROR_VALID_ARGUMENTS,errorMap);
    }
    /**
     * ConstraintViolationException异常
     * 散装参数校验 即不是封装得Dto
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    public Result<ExceptionEnum> handleValidtorException(ConstraintViolationException e) {
        log.warn("参数错误: {}", e.getMessage(), e);
        // 一般只需返回泛化的错误信息，比如“参数错误”
        return Result.error(ExceptionEnum.ERROR_VALID_ARGUMENTS,e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<ExceptionEnum> handleRuntimeException(RuntimeException e){
        log.warn("运行时异常:{}",e.getMessage(),e);
        return Result.error(ExceptionEnum.ERROR,"系统异常请联系管理员");
    }
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<ExceptionEnum> handleIllegalArgumentException(IllegalArgumentException e){
        log.warn("非法参数异常:{}",e.getMessage(),e);
        return Result.error(ExceptionEnum.ERROR,"请检查参数是否有误");
    }
}
